from django import forms
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.urls import reverse

from app01 import models
from app01.models import TransactionRecord
from app01.utils.script.bootstrap import BootStrapForm
from app01.utils.encrypt.md5 import md5
from app01.utils.script.response import BaseResponse
from app01.utils.script.pager import Paginator
from app01.utils.script.link import filter_reverse



def user_list(request):
    keyword = request.GET.get('keyword',"").strip()
    con = Q()
    if keyword:
        con.connector = "OR"
        con.children.append(("name__contains",keyword))
        con.children.append(("mobile__contains",keyword))
        con.children.append(("leval__title__contains",keyword))


    queryset = models.Customer.objects.filter(con).filter(active=1).select_related('leval')
    pager = Paginator(request, queryset)
    # page_string = obj.html()

    context = {
        # 'queryset': queryset[obj.start:obj.end],
        # 'page_string': page_string,
        'pager':pager,
        'keyword': keyword
    }
    return render(request, 'user_list.html', context)

class UserModelForm(BootStrapForm, forms.ModelForm):
    exclude_filed_list = ['leval']

    confirm_password = forms.CharField(
        label="重复密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Customer
        fields = ['name', 'mobile','password','confirm_password','leval']
        widgets = {
            'password': forms.PasswordInput(render_value=True),
            'leval': forms.RadioSelect(attrs={'class': "form-radio"})
        }
    def clean_password(self):
        password = self.cleaned_data["password"]
        return md5(password)
    def clean_confirm_password(self):
        password = self.cleaned_data.get("password")
        confirm_password = md5(self.cleaned_data.get("confirm_password",""))
        if confirm_password != password:
            raise ValidationError("两次密码不一样")
        return confirm_password
    def __init__(self,request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["leval"].queryset = models.Leval.objects.filter(active=1)
def user_add(request):
    if request.method == 'GET':
        form = UserModelForm(request)
        return render(request,"form2.html",{"form":form})
    form = UserModelForm(request,data=request.POST)
    if not form.is_valid():
        return render(request,"form2.html",{"form":form})
    form.save()
    return redirect('/customer/list/')
class UserEditModelForm(BootStrapForm,forms.ModelForm):
    class Meta:
        model = models.Customer
        fields = ['name', 'mobile', 'leval']
    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['leval'].queryset = models.Leval.objects.filter(active=1)
def user_edit(request,pk):
    # param_url = request.GET.get("_filter")
    base_url = reverse('customer_list')
    # print(base_url)
    url = filter_reverse(request,base_url)
    # print(url)
    customer_obj = models.Customer.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = UserEditModelForm(request, instance=customer_obj)
        return render(request,"form2.html",{"form":form})
    form = UserEditModelForm(request,instance=customer_obj,data=request.POST)
    if not form.is_valid():
        return render(request,"form2.html",{"form":form})
    form.save()
    return redirect(url)

class UserResetModelForm(BootStrapForm,forms.ModelForm):
    confirm_password = forms.CharField(
        label="重复密码",
        widget=forms.PasswordInput(render_value=True)
    )
    class Meta:
        model = models.Customer
        fields = ['password',"confirm_password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }
    def clean_password(self):
        password = self.cleaned_data["password"]
        return md5(password)
    def clean_confirm_password(self):
        password = self.cleaned_data.get("password")
        confirm_password = self.cleaned_data.get("confirm_password","")
        if password != md5(confirm_password):
            raise ValidationError("两次密码不一样")
        return confirm_password
def user_reset(request,pk):
    if request.method == 'GET':
        form = UserResetModelForm()
        return render(request,"form2.html",{"form":form})
    customer_obj = models.Customer.objects.filter(id=pk).first()
    form = UserResetModelForm(instance=customer_obj,data=request.POST)
    if not form.is_valid():
        return render(request,"form2.html",{"form":form})
    form.save()
    return redirect('/customer/list/')

def user_delete(request):
    cid = request.GET.get("cid",0)
    res = BaseResponse()
    if not cid:
        res.detail="请选择要删除的用户"
        return JsonResponse(res.dict)
    exists = models.Customer.objects.filter(id=cid,active=1).exists
    if not exists:
        res.detail="用户名不存在"
    models.Customer.objects.filter(id=cid, active=1).update(active=0)
    res.status = True
    return JsonResponse(res.dict)
class CustomerCharge(BootStrapForm, forms.ModelForm):
    charge_type = forms.TypedChoiceField(
        label="类型",
        choices=[(1, '充值'), (2, '扣款')],
        coerce=int
    )
    class Meta:
        model = models.TransactionRecord
        fields = ['charge_type', 'amount']
def user_charge(request,pk):
    queryset = models.TransactionRecord.objects.filter(customer_id=pk,customer__active=1,active=1).select_related('customer').order_by('-id')
    pager = Paginator(request,queryset)
    form = CustomerCharge()
    # print(locals())
    return render(request,"charge.html",locals())

def charge_add(request,pk):
    form = CustomerCharge(data=request.POST)
    if not form.is_valid():
        return JsonResponse({"status":False,'detail':form.errors})
    # print(form.cleaned_data)

    charge_type = form.cleaned_data['charge_type']
    amount = form.cleaned_data['amount']
    print(charge_type,amount)
    from django.db import transaction
    try:
        with transaction.atomic():
            cus_obj = models.Customer.objects.filter(id=pk, active=1).select_for_update().first()
            if charge_type == 2 and amount > cus_obj.balance:
                return JsonResponse({"status":False,'detail':{"amount":["余额不足，还剩{}元".format(cus_obj.balance)]}})
            if charge_type == 1:
                cus_obj.balance += amount
            else:
                cus_obj.balance -= amount
            cus_obj.save()
            form.instance.customer = cus_obj
            form.instance.creator_id = request.user.id
            form.save()
    except Exception as e:
        return JsonResponse({"status":False,'detail':{"amount":["操作失败"]}})

    return JsonResponse({"status":True})




